﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Threading;
using System.Security.Cryptography;
namespace IntelligentGateway.Tools
{
    public class UTools
    {
        public static int CredNumber = 0;
        public static int GetCredNumber()
        {
            if (CredNumber > int.MaxValue) CredNumber = 1;
            return Interlocked.Add(ref CredNumber, 1);
           
        }
        public static  byte[] GetCredNumByte()
        {
            int temp = GetCredNumber();
            byte[] result = BitConverter.GetBytes(temp);
            return result;
        }
        public static string ToHexs(byte[] data, string spit = ",")
        {
            StringBuilder sb = new StringBuilder();
            for (int i = 0; i < data.Length; i++)
            {
                sb.Append(data[i].ToString("X2"));

                sb.Append(spit);
            }
            string str = sb.ToString();
            if (str.Equals("")) return "";
            return str = string.IsNullOrEmpty(spit) ? str : str.Substring(0, str.Length - 1);
        }
        public static byte[] ComputeCrc16(byte[] bytes)
        {
            ushort crc = 0xFFFF;
            for (int i = 0; i < bytes.Length; i++)
            {
                crc = (ushort)(crc ^ bytes[i]);
                for (int j = 0; j < 8; j++)
                {
                    crc = (crc & 0x0001) != 0 ? (ushort)((crc >> 1) ^ 0xA001) : (ushort)(crc >> 1);
                }
            }

            return BitConverter.GetBytes(crc);
        }
        public static string MD5(string str)
        {
            //微软md5方法参考return FormsAuthentication.HashPasswordForStoringInConfigFile(str, "md5");
            byte[] b = Encoding.Default.GetBytes(str);
            b = new MD5CryptoServiceProvider().ComputeHash(b);
            string ret = "";
            for (int i = 0; i < b.Length; i++)
                ret += b[i].ToString("x").PadLeft(2, '0'); //转成16进制，如果小于2位用0补充
            return ret;
        }
        public static DateTime ConvertTimestampToDate(long timestamp)
        {
            DateTime epoch = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc);
            return epoch.AddSeconds(timestamp).ToLocalTime();
        }
    }   
}
